package com.youlu.campus.service.vote;

import com.google.common.collect.Lists;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.entity.vote.UserVotePointEntity;
import com.youlu.campus.entity.vote.VoteConstant;
import com.youlu.campus.entity.vote.VoteOrganizationInfo;
import com.youlu.campus.entity.vote.VoteSimpleActivityEntity;
import com.youlu.campus.entity.vote.dto.UserVoteRankInfoDTO;
import com.youlu.campus.entity.vote.dto.VoteHomeSearchDTO;
import com.youlu.campus.entity.vote.dto.VotePointOpDTO;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.ranking.UserActivityPointDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author : [dengbo]
 * @className : ActivityVoteService
 * @description : [活动投票服务]
 * @createTime : [2022/7/7 00:06]
 */
@Service
@Slf4j
public class ActivityVoteService {
    @Autowired
    private VoteOrganizationService voteOrganizationService;
    @Autowired
    private SimpleActivityService simpleActivityService;
    @Autowired
    private UserVoteService userVoteService;
    @Autowired
    private UserActivityPointDetailService userActivityPointDetailService;
    @Autowired
    private ActivityVoteRedisService activityVoteRedisService;
    @Autowired
    private UserInviteRecordService userInviteRecordService;
    @Autowired
    private ActivityTaskService activityTaskService;

    public UserVoteRankInfoDTO getUserVoteRankInfo(String activityId, String appId, String userId, UserPO userPO) {
        UserVoteRankInfoDTO dto = new UserVoteRankInfoDTO();
        List<String> fields = Lists.newArrayList("id", "startTime", "endTime", "receiveCertTitle", "receiveCertCondition", "orgTypeId", "receiveCertSuccessImageUrl");
        VoteSimpleActivityEntity activityInfo = simpleActivityService.findFieldsById(activityId, fields, VoteSimpleActivityEntity.class);
        if (activityInfo == null) {
            return dto;
        }
        dto.setReceiveCertCondition(activityInfo.getReceiveCertCondition());
        dto.setReceiveCertTitle(activityInfo.getReceiveCertTitle());
        dto.setReceiveCertSuccessImageUrl(activityInfo.getReceiveCertSuccessImageUrl());
        // 查询用户票数信息
        UserVotePointEntity point = userVoteService.findUserVotePoint(activityId, userId);
        if (point == null) {
            VoteHomeSearchDTO searchDTO = new VoteHomeSearchDTO();
            searchDTO.setUserPO(userPO);
            searchDTO.setUserId(userId);
            searchDTO.setAppId(appId);
            searchDTO.setActivityId(activityId);
            userVoteService.perDayVoteReceive(searchDTO, VoteConstant.PER_DAY_RECEIVE_NUM);
            return dto;
        }
        // 设置用户基本信息
        dto.setUserName(point.getUserName());
        dto.setMobile(point.getMobile());
        dto.setUniversityId(point.getUniversityId());
        dto.setUniversityName(point.getUniversityName());
        dto.setInViteCaReceive(point.getInViteCaReceive());
        dto.setVoteCaReceive(point.getVoteCaReceive());
        //查询用户票数
        Pair<String, Long> userRankInfo = activityVoteRedisService.getUserPersonalVoteRank(activityId, userId);
        // 设置用户排行信息
        dto.setUserTotalVoteNum(point.getTotalVoteNum());
        dto.setUserTotalNum(point.getTotalNum());
        Long scoreRank = userRankInfo.getRight() == null ? null : userRankInfo.getRight() + 1;
        dto.setUserRank(scoreRank);
        String schoolId = userPO.getUniversityId();
        //查询学校信息
        if (schoolId != null) {
            VoteOrganizationInfo info = voteOrganizationService.getOrgInfoByOrgId(activityInfo.getOrgTypeId(), schoolId);
            if (info != null) {
                // 设置学校排行信息
                dto.setOrgTotalNum(info.getTotalVoteNum());
                dto.setOrgRealNum(info.getRealVoteNum());
                // 查询学校排行
                Pair<String, Long> orgRankInfo = activityVoteRedisService.getAllUserVoteRank(activityId, info.getOrgCode());
                Long schoolRank = orgRankInfo.getRight() == null ? null : orgRankInfo.getRight() + 1;
                dto.setOrgRank(schoolRank);
            }
        }
        return dto;
    }

    /**
     *  添加用户投票信息
     * @param activityId
     * @param userId
     */
    @Async
    public void updateVoteInviteRecord(String activityId, String userId) {
        boolean re = userInviteRecordService.updateInvitedCount(userId, activityId);
        if (!re) {
            log.info("updateVoteInviteRecord,aid:{},uid:{} invite failure", activityId, userId);
            return;
        }
        UserInviteRecord record = userInviteRecordService.findByInvitedToUserId(userId, activityId);
        if (record == null || record.getInvitedByUserId() == null) {
            log.info("updateVoteInviteRecord,aid:{},uid:{} invite from user record not exist", activityId, userId);
            return;
        }
        String inviteUserId = record.getInvitedByUserId();
        // 增加邀请人投票数量
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        VotePointOpDTO opDTO = new VotePointOpDTO();
        opDTO.setUserId(inviteUserId);
        opDTO.setActivityId(activityId);
        if (activityTaskInfo != null) {
            int num = activityTaskInfo.getPoints().intValue();
            // 设置邀请数量
            opDTO.setNum(num);
            // 添加邀请明细
            addInviteDetail(activityId, inviteUserId, num);
        }
        // 设置邀请人数
        opDTO.setInviteNum(VoteConstant.INVITE_ADD_USER_NUM);
        userVoteService.updateVoteNum(opDTO);
        log.info("updateVoteInviteRecord,aid:{},uid:{} invite success from userId:{}", activityId, userId, inviteUserId);
    }

    /**
     * 添加邀请记录
     * @param activityId
     * @param userId
     * @param num
     */
    public void addInviteDetail(String activityId, String userId, int num) {
        // 添加投票明细
        UserActivityPointDetail userActivityPointDetail = new UserActivityPointDetail();
        userActivityPointDetail.setAction("add");
        userActivityPointDetail.setActivityId(activityId);
        userActivityPointDetail.setBizDesc("邀请好友");
        userActivityPointDetail.setComments("邀请好友" + VoteConstant.INVITE_ADD_VOTE_NUM);
        userActivityPointDetail.setBizType("invite");
        userActivityPointDetail.setOptDate(new Date());
        userActivityPointDetail.setPoints(num);
        userActivityPointDetail.setCreatedTime(new Date());
        userActivityPointDetail.setUserId(userId);
        userActivityPointDetailService.save(userActivityPointDetail);
    }

    /**
     * 添加投票记录
     * @param activityId
     * @param userId
     */
    @Async
    public void saveVoteDetail(String activityId, String userId) {
        // 添加投票明细
        UserActivityPointDetail userActivityPointDetail = new UserActivityPointDetail();
        userActivityPointDetail.setAction("sub");
        userActivityPointDetail.setActivityId(activityId);
        userActivityPointDetail.setBizDesc("投票");
        userActivityPointDetail.setComments("投票" + VoteConstant.DEFAULT_VOTE_NUM);
        userActivityPointDetail.setBizType("vote");
        userActivityPointDetail.setOptDate(new Date());
        userActivityPointDetail.setPoints(VoteConstant.DEFAULT_VOTE_NUM);
        userActivityPointDetail.setUserId(userId);
        userActivityPointDetailService.save(userActivityPointDetail);
    }

    public Pair<Boolean, Integer> receiveVoteCa(String activityId, String userId) {
        return userVoteService.receiveUserVoteCa(activityId, userId);
    }

    public Pair<Boolean, Integer> receiveInViteCa(String activityId, String userId) {
        return userVoteService.receiveUserInViteCa(activityId, userId);
    }
}
